﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Security.Cryptography;
using System.Text;

public partial class login : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void imgbtn_Click(object sender, ImageClickEventArgs e)
    {
        CMSModel.CMSEntities dal = DAL.DBManager.GetCmsEmtity();
        string name = txtname.Text;
        string pwd = getMd5Hash(txtpassword.Text);
        EncryptClasses.DESEncrypt des = new EncryptClasses.DESEncrypt();
        try
        {
            CMSModel.User user = dal.User.First(x => x.LoginName.Contains(name)&&x.pwd.Contains(pwd));
            if (user != null && user.IsEnable != false)
            {
                Response.Cookies["loginname"].Value = user.LoginName;
                if (string.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
                {
                    Response.Redirect("~/index.aspx");
                }
                else
                {
                    Response.Redirect("~/" + Request.QueryString["ReturnUrl"] + ".aspx");
                }
            }
            else
            {
                ClientScript.RegisterStartupScript(GetType(), "login", "alert('用户已禁用！');document.location='Login.aspx'", true);
            }
        }
        catch (Exception ex)
        {
            LogYuMin.LogWriter.GetWriter(LogYuMin.LogFile.error).Write(GetType(), "Login", LogYuMin.LogStates.ERROR, ex);
            ClientScript.RegisterStartupScript(GetType(), "login", "alert('密码或用户名错误!');document.location='Login.aspx'", true);
        }
    }
    /// <summary>
    /// 加密字符串
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    static string getMd5Hash(string input)
    {
        // Create a new instance of the MD5CryptoServiceProvider object.
        MD5 md5Hasher = MD5.Create();

        // Convert the input string to a byte array and compute the hash.
        byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(input));

        // Create a new Stringbuilder to collect the bytes
        // and create a string.
        StringBuilder sBuilder = new StringBuilder();

        // Loop through each byte of the hashed data 
        // and format each one as a hexadecimal string.
        for (int i = 0; i < data.Length; i++)
        {
            sBuilder.Append(data[i].ToString("x2"));
        }

        // Return the hexadecimal string.
        return sBuilder.ToString();
    }
}
